<?php

namespace Admin\Controller;

use Common\Service\Dictionary;

class OrderController extends CommonController
{
    /**
     * 订单管理----首页
     */
    public function index()
    {
        $order = M('Orders');
        if ($_GET) {
            //模糊查询
            $order_no = I('get.order_no');
            $name = I('get.name');
            $tel = I('get.tel');
            $created_at = I('get.created_at');
            $status = I('get.status');

            //按订单号
            if ($order_no) {
                $map['order_no'] = array('like', "%" . $order_no . "%");
            }
            //按姓名查找
            if ($name) {
                $map['name'] = array('like', "%" . $name . "%");
            }
            //按手机号
            if ($tel) {
                $map['tel'] = array('like', "%" . $tel . "%");
            }
            //按时间查找
            if (!empty($created_at)) {
                $time = explode(" ~ ", $created_at);
                //把字符串转换成数组
                $times[] = strtotime($time[0] . ' 00:00:00');//这里单引号前面要打一空格
                $times[] = strtotime($time[1] . ' 23:59:59');
                $map['created_at'] = array('between', $times);
            }
            //按状态
            if ($status) {
                $map['status'] = array('like', "%" . $status . "%");
            }
        }

        $count = $order->count();// 查询满足要求的总记录数
        $Page = new \Common\Util\Page($count, 5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $pages = $Page->show();// 分页显示输出
        $orders = $order->alias('a')->where($map)->order('created_at desc')
            ->field('a.*,b.address,b.tel,b.name')
            ->join('address AS b ON b.id=a.address_id', 'LEFT')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();

        //调用静态方法查出所有订单状态
        $orderStatus = Dictionary::orderStatus();

        $this->assign(compact('orders', 'orderStatus','pages', 'count'));
        $this->display();
    }

    /**
     * 订单管理---查看订单
     */
    public function show()
    {
        $product = M('Product');
        $order = M('Orders');

        $id = I('get.id');
        $orders = $order->where("id = '$id'")->find();
        //查询订单对应的地址
        $address = $this->address->where("id = '$orders[address_id]'")->find();

        //查询订单对应的商品
        //表连表查询(a:product b:order_product,c:order)
        $products = $product->alias('a')
            ->field('a.name,a.price,b.number,a.price*b.number as total,c.total_price')
            ->join('order_product AS b ON b.product_id = a.id', 'LEFT')
            ->join('orders AS c ON c.id = b.order_id', 'LEFT')
            ->where(array('b.order_id' => $id))
            ->select();

        $this->assign(compact('address', 'products'));
        $this->display();
    }

}